﻿using DLC.Module.DataTable.Default;
using System;
using System.Reflection;
using System.Text;
using UnityEngine;

namespace DLC.Module.DataTable.ArchiveString
{
    public class DataTableString<T> : DataTable<T>, IDataTableString where T : class, IDataRow, new()
    {
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            PropertyInfo[] p = Type.GetProperties();
            foreach (var dataRow in GetAllDataRows())
            {
                for (int i = 0; i < p.Length; i++)
                {
                    var property = p[i];
                    var value = property.GetValue(dataRow, null);
                    var val = ConvertExt.ConvertToString(value, property.PropertyType, property.GetCustomAttribute<DelimitersAttribute>());
                    sb.Append(val).Append(Constant.DelimiterCharTab);
                }
                sb.Append(Constant.DelimiterCharNewLine);
            }
            return sb.ToString();
        }

        public bool ParseFromString(string data)
        {
            RemoveAllDataRows();
            string[] dataRows = data.Split(Constant.DelimiterCharNewLine);
            PropertyInfo[] p = Type.GetProperties();
            foreach (var dataRow in dataRows)
            {
                if (string.IsNullOrEmpty(dataRow)) continue;
                string[] datas = dataRow.Split(Constant.DelimiterCharTab);
                var item = (T)Activator.CreateInstance(Type);
                for (int i = 0; i < p.Length; i++)
                {
                    try
                    {
                        var property = p[i];
                        string val = "";
                        if (datas.Length > i)
                        {
                            val = datas[i];
                        }
                        var value = ConvertExt.ConvertFromString(val, property.PropertyType, property.GetCustomAttribute<DelimitersAttribute>());
                        property.SetValue(item, value, null);
                    }
                    catch (Exception e)
                    {
                        Debug.LogError($"ParseFromString Error. Deserialize Exception: {e.Message} at {datas[i]}");
                    }
                }
                AddDataRow(item);
            }
            return true;
        }
    }
}
